<template>
  <a-drawer
    v-model:visible="vdata.isShow"
    :title="vdata.isAdd ? '新增操作员' : '修改操作员'"
    placement="right"
    :closable="true"
    width="75%"
    :maskClosable="false"
    @ok="handleOkFunc"
    @close="onClose"
  >
    <!-- <a-modal :confirmLoading="confirmLoading"> -->
 
    <a-form
      ref="infoFormModel"
      :model="vdata.saveObject"
      :rules="rules"
      style="padding-bottom:50px"
      layout="vertical"
    >
      <a-row justify="space-between" type="flex">
        <a-col :span="10">
          <a-form-item label="用户登录名:" name="loginUsername">
            <a-input v-model:value="vdata.saveObject.loginUsername" :disabled="!vdata.isAdd" />
          </a-form-item>
        </a-col>

        <a-col :span="10">
          <a-form-item label="用户姓名：" name="realname">
            <a-input v-model:value="vdata.saveObject.realname" />
          </a-form-item>
        </a-col>

        <a-col :span="10">
          <a-form-item label="手机号：" name="telphone">
            <a-input v-model:value="vdata.saveObject.telphone" />
          </a-form-item>
        </a-col>

        <a-col :span="10">
          <a-form-item label="编号：" name="userNo">
            <a-input v-model:value="vdata.saveObject.userNo" />
          </a-form-item>
        </a-col>

        <a-col :span="10">
          <a-form-item label="请选择性别：" name="sex">
            <a-radio-group v-model:value="vdata.saveObject.sex">
              <a-radio :value="1">男</a-radio>
              <a-radio :value="2">女</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>

        <a-col :span="10">
          <a-form-item label="状态：" name="state">
            <a-radio-group v-model:value="vdata.saveObject.state">
              <a-radio :value="1">启用</a-radio>
              <a-radio :value="0">停用</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>

        <a-col :span="10">
          <a-form-item v-if="(userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" label="用户类型：" name="userType">
            <a-select v-model:value="vdata.saveObject.userType" placeholder="请选择用户类型" defaultValue="2" @change="handleChange">
              <a-select-option v-if="(userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" :value="1">超级管理员</a-select-option>
              <a-select-option v-if="(userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" :value="2">普通操作员</a-select-option>
              <a-select-option v-if="(userStore.userInfo['userType'] != '11' && userStore.userInfo['userType'] != '12')" :value="11">店长</a-select-option>
              <a-select-option :value="12">店员</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <!-- 登录用户为店长并且当前用户为店长 不显示门店列表（无意义，无法修改） -->
        <a-col v-if="!(vdata.saveObject.userType == '11' && userStore.userInfo['userType'] == '11')" :span="24">
          <!-- 仅当用户类型为店长、店员时显示该门店列表 -->
          <a-col v-if="vdata.saveObject.userType == '11' || vdata.saveObject.userType == '12'" :span="24">
            <a-form-item label="权限配置" name="rulesList">
              <a-checkbox-group v-model:value="vdata.saveObject.rulesList">
                <a-checkbox v-if="vdata.saveObject.userType == '11'" value="USER_TYPE_11_INIT">店长默认权限</a-checkbox>
                <a-checkbox v-if="vdata.saveObject.userType == '11'" value="STORE">门店管理权限</a-checkbox>
                <a-checkbox v-if="vdata.saveObject.userType == '12'" value="USER_TYPE_12_INIT">店员默认权限</a-checkbox>
                <a-checkbox v-if="vdata.saveObject.userType == '12'" value="QUICK_PAY">快捷收银权限</a-checkbox>
                <a-checkbox v-if="vdata.saveObject.userType == '12'" value="REFUND">退款权限</a-checkbox>
                <a-checkbox v-if="vdata.saveObject.userType == '12'" value="DEVICE">设备管理权限</a-checkbox>
                <a-checkbox v-if="vdata.saveObject.userType == '12'" value="STATS">统计报表权限</a-checkbox>
              </a-checkbox-group>
            </a-form-item>
            <a-divider orientation="left">
              <a-tag color="#FF4B33">绑定门店</a-tag>
            </a-divider>
            <div class="modal-div">
              <!-- 门店列表 -->
              <div class="modal-div1">
                <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="resetFunc">
                  <jeepay-text-up v-model:value="vdata.searchData['storeId']" :placeholder="'门店ID'" />
                  <jeepay-text-up v-model:value="vdata.searchData['storeName']" :placeholder="'门店名称'" />
                </JeepaySearchForm>

                <div class="list-table">
                  <JeepayTable
                    ref="infoTable"
                    :initData="false"
                    :reqTableDataFunc="reqTableDataFunc"
                    :tableColumns="tableColumns"
                    :searchData="vdata.searchData"
                    rowKey="storeId"
                    scrollX="100%"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.key === 'storeId'">
                        {{ record.storeId }}
                      </template>

                      <template v-if="column.key === 'storeName'">
                        {{ record.storeName }}
                      </template>

                      <template v-if="column.key === 'bindState'">
                        <JeepayTableColState :badgeTextArray="['未绑店长', '已绑店长', '未知']" :state="vdata.selectRecordIdList.includes(record.storeId) ? 1 : 0" :showSwitchType="!record.hasDirector? true: false" :onChange="(state) => { return updateBindState(record.storeId, state)}" />
                      </template>
                    </template>
                  </JeepayTable>
                </div>
              </div>
            </div>
          </a-col>
        </a-col>
      </a-row>
      <a-divider orientation="left">
        <a-tag color="#FF4B33">账户安全</a-tag>
      </a-divider>
      <div v-if="vdata.isAdd">
        <a-row justify="space-between" type="flex">
          <a-col :span="24">
            <a-form-item label="是否发送开通提醒">
              <a-radio-group v-model:value="vdata.saveObject['isNotify']">
                <a-radio :value="0">否</a-radio>
                <a-radio :value="1">是</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="密码设置">
              <a-radio-group v-model:value="vdata.saveObject['passwordType']">
                <a-radio value="default">默认密码</a-radio>
                <a-radio value="custom">自定义密码</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
          <a-col v-if="vdata.saveObject['passwordType'] == 'custom'" :span="12">
            <a-form-item label="登录密码" name="loginPassword">
              <a-input
                v-model:value="vdata.saveObject['loginPassword']"
                placeholder="请输入登录密码"
              />
            </a-form-item>
            <a-button type="primary" ghost @click="randomPassage(false, 6, 0)"><file-sync-outlined />随机生成密码</a-button>
          </a-col>
        </a-row>
      </div>

      <div v-else>
        <div style="display:flex;flex-direction:row;">
          <a-row justify="space-between" type="flex" style="width:100%">
            <a-col :span="10">
              <a-form-item v-if="vdata.resetIsShow" label>
                重置密码：
                <a-checkbox v-model:checked="vdata.sysPassword.resetPass" />
              </a-form-item>
            </a-col>
            <a-col :span="10">
              <a-form-item v-if="vdata.sysPassword.resetPass" label>
                恢复默认密码：
                <a-checkbox v-model:checked="vdata.sysPassword.defaultPass" @click="isResetPass" />
              </a-form-item>
            </a-col>
          </a-row>
        </div>

        <div v-if="vdata.sysPassword.resetPass">
          <div v-show="!vdata.sysPassword.defaultPass">
            <a-row justify="space-between" type="flex">
              <a-col :span="10">
                <a-form-item label="新密码:" name="newPwd">
                  <a-input-password
                    v-model:value="vdata.newPwd"
                    autocomplete="new-password"
                    :disabled="vdata.sysPassword.defaultPass"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="10">
                <a-form-item label="确认新密码:" name="confirmPwd">
                  <a-input-password
                    v-model:value="vdata.sysPassword.confirmPwd"
                    autocomplete="new-password"
                    :disabled="vdata.sysPassword.defaultPass"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </div>
        </div>
      </div>
      

      <div class="drawer-btn-center">
        <a-button :style="{ marginRight: '8px' }" @click="onClose">
          <close-outlined />取消
        </a-button>
        <a-button type="primary" :loading="vdata.confirmLoading" @click="handleOkFunc">
          <check-outlined />保存
        </a-button>
      </div>
    </a-form>
  </a-drawer>
</template>

<script lang="ts" setup>
import { req, API_URL_SYS_USER_LIST, $getPasswordRules, API_URL_MCH_STORE_LIST } from '@/api/manage'
import { useUserStore } from '@/store/modules/user'
import { Base64 } from 'js-base64'
import { message } from 'ant-design-vue'
import { reactive, ref, nextTick } from 'vue'

const userStore = useUserStore()
const infoFormModel = ref()
const props = defineProps({
	callbackFunc: {
		type: Function,
		default: () => ({})
	}
})

const tableColumns = ref([
  { key: 'storeId', title: '门店ID'},
  { key: 'storeName', title: '门店名称'},
  { key: 'bindState', title: '绑定状态'},
])

// 当前 table 组件
const infoTable = ref()

const vdata :any = reactive({
	newPwd: '', //  新密码
	resetIsShow: false, // 重置密码是否展现
  passwordRules: /^$/,//密码规则
  passwordRulesText: '', //密码规则提示文字
	sysPassword: {
		resetPass: false, // 重置密码
		defaultPass: true, // 使用默认密码
		confirmPwd: '' //  确认密码
	},
	loading: false, // 按钮上的loading
	value: 1, // 单选框默认的值
	confirmLoading: false, // 显示确定按钮loading图标
	isAdd: true, // 新增 or 修改页面标识
	isShow: false, // 是否显示弹层/抽屉
	saveObject: {} as any, // 数据对象
	recordId: null, // 更新对象ID	
  searchData: {},
  selectRecordIdList: [],
})
const rules = {
	realname: [{
		required: true,
		message: '请输入用户姓名',
		trigger: 'blur'
	}],
	telphone: [{
		required: true,
		pattern: /^[1][0-9]{10}$/,
		message: '请输入正确的手机号码',
		trigger: 'blur'
	}],
	userNo: [{ required: true, message: '请输入编号', trigger: 'blur' }],
	userType: [{ required: true, message: '请选择用户类型', trigger: 'blur' }],
	rulesList: [{ required: true, message: '请选择权限配置', trigger: 'blur' }],
	loginUsername: [] as any[],
	newPwd: [{
		required: false,
		trigger: 'blur'
	}, {
		validator: (rule, value) => {
          if (!vdata.sysPassword.defaultPass) {
            if (!vdata.passwordRules.test(vdata.newPwd)) {
              return Promise.reject(vdata.passwordRulesText)
            } else if(vdata.newPwd !== vdata.sysPassword.confirmPwd) {
              return Promise.reject('新密码与确认密码不一致')
            } else return Promise.resolve()
          } else {
              return Promise.resolve()
          }
        }
	}], // 新密码
	confirmPwd: [{
		required: false,
		trigger: 'blur'
	}, {
		validator: (rule, value) => {
          if (!vdata.sysPassword.defaultPass) {
            // vdata.newPwd === vdata.sysPassword.confirmPwd ? callBack() : callBack('新密码与确认密码不一致')
            if(!vdata.passwordRules.test(vdata.sysPassword.confirmPwd)){
              return Promise.reject(vdata.passwordRulesText)
            } else if(vdata.newPwd !== vdata.sysPassword.confirmPwd) {
              return Promise.reject('新密码与确认密码不一致')
            } else return Promise.resolve()
          } else {
              return Promise.resolve()
          }
        }
	}] // 确认新密码
}
function getPasswordRules () { // 获取密码规则
    $getPasswordRules().then(res => {
      vdata.passwordRules = new RegExp(res.regexpRules)
      vdata.passwordRulesText = res.errTips
    })
}
defineExpose({ show })
function show(recordId) { // 弹层打开事件
  // 已选门店ID置空
  vdata.selectRecordIdList = []

  getPasswordRules()
	if (infoFormModel.value !== undefined) {
		infoFormModel.value.resetFields()
	}

	vdata.isAdd = !recordId
	// 数据恢复为默认数据
	vdata.saveObject = { state: 1, sex: 1, passwordType: 'default', isNotify: 0, userType: 1 }
  
	rules.loginUsername = []
	vdata.confirmLoading = false // 关闭loading

	if (vdata.isAdd) {
    // 新增页面用户ID置空
    vdata.recordId = null
		rules.loginUsername.push({
			required: true,
			pattern: /^[a-zA-Z][a-zA-Z0-9]{5,17}$/,
			message: '请输入字母开头，长度为6-18位的登录名',
			trigger: 'blur'
		})
	} else { // 修改信息 延迟展示弹层
		vdata.resetIsShow = true // 展示重置密码板块
		vdata.recordId = recordId
		req.getById(API_URL_SYS_USER_LIST, recordId).then(res => {
			vdata.saveObject = res
      // 拉取门店列表
      if((vdata.saveObject.userType == '11' || vdata.saveObject.userType == '12') && userStore.userInfo['userType'] != '11'){
        nextTick(() => infoTable.value.refTable(true))
      }
      // 如果用户绑定门店信息不为空，为绑定门店ID赋值
      if(vdata.saveObject.storeIdList) {
        vdata.selectRecordIdList = vdata.saveObject.storeIdList
      }
		})
	}

  vdata.isShow = true // 立马展示弹层信息

  // 当前登录用户为店长，默认值为店员
  if (userStore.userInfo['userType'] == '11') {
    vdata.saveObject.userType = 12
    nextTick(() => infoTable.value.refTable(true))
  }

}
function handleOkFunc() { // 点击【确认】按钮事件
	infoFormModel.value.validate().then(valid => {
		vdata.loading = true // 打开按钮上的 loading
		vdata.confirmLoading = true // 显示loading

    // 参数转化
    if(vdata.saveObject.userType == '11' || vdata.saveObject.userType == '12'){
      vdata.saveObject.storeIdList = vdata.selectRecordIdList.join(',')

      // 是否为用户绑定门店，如果未绑定则提示需绑定门店
      if(!vdata.saveObject.storeIdList) {
        vdata.confirmLoading = false
          return message.error('请为此用户绑定门店')
        }
    }

		if (vdata.isAdd) {
      if(!vdata.saveObject.loginPassword) {
        vdata.saveObject.loginPassword = ''
      }
      if(vdata.saveObject.passwordType == 'custom' && !vdata.passwordRules.test(vdata.saveObject.loginPassword)) {
        vdata.confirmLoading = false
        return message.error(vdata.passwordRulesText)
      }

			req.add(API_URL_SYS_USER_LIST, vdata.saveObject).then(res => {
				message.success('新增成功')
				vdata.isShow = false
				vdata.loading = false
				props.callbackFunc() // 刷新列表
			}).catch((res) => {
				vdata.confirmLoading = false
			})
		} else {

      let sysPasswordCopy = Object.assign({}, vdata.sysPassword)
			sysPasswordCopy.confirmPwd = Base64.encode(sysPasswordCopy.confirmPwd)
			Object.assign(vdata.saveObject, sysPasswordCopy) // 拼接对象
			req.updateById(API_URL_SYS_USER_LIST, vdata.recordId, vdata.saveObject).then(res => {
				message.success('修改成功')
				vdata.isShow = false
				props.callbackFunc() // 刷新列表
				vdata.resetIsShow = false // 取消展示
				vdata.sysPassword.resetPass = false
				vdata.sysPassword.defaultPass = true	// 是否使用默认密码默认为true
				resetPassEmpty(vdata) // 清空密码
			}).catch(res => {
				vdata.confirmLoading = false
			})
		}
	})
}
// 点击遮罩层关闭抽屉
function onClose() {
	vdata.isShow = false
	vdata.resetIsShow = false // 取消重置密码板块展示
	resetPassEmpty(vdata) // 清空密码
	vdata.sysPassword.resetPass = false // 关闭密码输入
	vdata.sysPassword.defaultPass = true	// 是否使用默认密码默认为true
}
// 使用默认密码重置是否为true
function isResetPass() {
	if (!vdata.sysPassword.defaultPass) {
		vdata.newPwd = ''
		vdata.sysPassword.confirmPwd = ''
	}
}
// 保存后清空密码
function resetPassEmpty(that) {
	vdata.newPwd = ''
	vdata.sysPassword.confirmPwd = ''
}

function randomPassage(randomFlag, min, max) { // 生成6位随机密码
  let str = ''
  let range = min
  const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    var pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[ pos ]
  }
  vdata.saveObject['loginPassword'] = str
}

// 表格搜索
function searchFunc () {
  nextTick(() => {
    infoTable.value.refTable(true)
  })
}

function resetFunc(){ 
  vdata.searchData = {} 
  vdata.cycleType = 'date'
}

// 请求table接口数据
function reqTableDataFunc (params){
  return req.list(API_URL_MCH_STORE_LIST + `/bindStoreList`, Object.assign({ userId: vdata.recordId, userType: vdata.saveObject.userType }, params))
}

// 表格行开关开启、关闭
function updateBindState(recordId, bindState) {
  return new Promise<void>((resolve, reject) => {
     nextTick(() => {
      if (bindState) {
        if(vdata.saveObject.userType == '12') {
          vdata.selectRecordIdList = []
        }
        vdata.selectRecordIdList.push(recordId)
      } else {
        vdata.selectRecordIdList.splice(vdata.selectRecordIdList.indexOf(recordId), 1)
      }
      console.log(vdata.selectRecordIdList)
      resolve()
    })
  })
}

function handleChange (value) {
  vdata.selectRecordIdList = []
  nextTick(() => infoTable.value.refTable(true))
}

</script>
